package com.unsiv.blplayer;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * @author fanzhen
 * @time 12:20:39 PM Sep 25, 2011
 * @email fanzhen.meng@gmail.com
 */
public class BluetoothPenService extends Service {
	private static final String TAG = "BluetoothChatService";
	public static final String COMMAND_COMING = "com.unisv.btpen.BluetoothPenService.action.COMMAND_COMING";
	public static final String COMMAND_TAG = "com.unisv.btpen.BluetoothPenService.msg.COMMAND_TAG";
    private static final String NAME = "BluetoothPen";
	private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
	private BluetoothAdapter mAdapter;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		this.mAdapter = BluetoothAdapter.getDefaultAdapter();
        Thread acceptThread = new AcceptThread();
        acceptThread.start();
	}
	private void announceCommandComing(String msg){
		Intent intent = new Intent(COMMAND_COMING);
		intent.putExtra(COMMAND_TAG, msg);
		sendBroadcast(intent);
	}
	class AcceptThread extends Thread {
		private final BluetoothServerSocket mmServerSocket;
		public AcceptThread() {
			BluetoothServerSocket tmp = null;
			try {
				tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
			} catch (IOException e) {
				Log.e(TAG, "listen() failed", e);
			}
			mmServerSocket = tmp;
		}
		public void run() {
			Log.d(TAG, "BEGIN mAcceptThread" + this);
			setName("AcceptThread");
			BluetoothSocket socket = null;
			while (true) {
				try {
					socket = mmServerSocket.accept();
					if (socket != null) {
						BufferedReader in = new BufferedReader(
								new InputStreamReader(socket.getInputStream()));
						String line=null;
						while ((line = in.readLine()) != null) {
							Log.d(TAG, line);
							announceCommandComing(line);
						}
					}
				} catch (IOException e) {
					Log.e(TAG, "accept() failed", e);
					break;
				}
			}
			Log.i(TAG, "END mAcceptThread");
		}
		public void cancel() {
			Log.d(TAG, "cancel " + this);
			try {
				mmServerSocket.close();
			} catch (IOException e) {
				Log.e(TAG, "close() of server failed", e);
			}
		}
	}
}